package com.hshx.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.hshx.VO.RecordVo;
import com.hshx.VO.RecordVo2;
import com.hshx.client.DeptClient;
import com.hshx.client.PositionClient;
import com.hshx.client.UsersClient;
import com.hshx.message.IMessageService;
import com.hshx.pojo.*;
import com.hshx.pojo.Record;
import com.hshx.service.RecordService;
import com.hshx.service.ResumeService;
import com.hshx.util.RedisUtil1;
import com.hshx.util.Util;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin
@RequestMapping("/zhaopingService")
@RestController
public class RecordController {


    @Resource
    private RecordService rdService;

    @Resource
    private UsersClient usersClient;

    @Resource
    private ResumeService rmService;

    @Autowired
    private RedisUtil1 redisUtil1;

    @Resource
    private IMessageService iMessageService;


    @Resource
    private DeptClient deptClient;
    @Resource
    private PositionClient positionClient;

    @RequestMapping(value = "/getAllRecord")
    public List<RecordVo>  getAllRecord(int page, int limit, String danganbianma) throws ParseException {

        if (danganbianma.equals("1")){
            danganbianma = "";
        }


        List<RecordVo> recordVos = new ArrayList<>();
        //1、判断redis是否存在
        if (null != getRedis("recordListPage", page, limit)) {//数据存在redis中，直接使用
            recordVos = getRedis("recordListPage", page, limit);
        } else {//数据失效，重新生成

            Resume resume = null;

            PageHelper.startPage(page,limit);//开始分页
            //查询获得主体档案集合【条件档案编号模糊查询，未被删除的】
            List<Record> records = rdService.list(new QueryWrapper<Record>()
                    .eq("record_delete", 2)
                    .like("record_no",danganbianma));
//            PageInfo<Record> pageInfo = new PageInfo<Record>(records);
            System.out.println("===========================================");
            records.forEach(System.out::println);
            System.out.println("===========================================");

            for (Record rd : records) {//遍历档案集合
                RecordVo recordVo = new RecordVo();//创建档案界面对象

                /* -------------- 档案表日期字段的转换*/
                java.sql.Date resultDate = Util.timeConvert(rd.getRecord_date());

                resume = rmService.getOne(
                        new QueryWrapper<Resume>().eq("resume_id", rd.getRecord_resume()));
                if(resume!=null){
                    /* --------------- 简历表两个日期字段的转换  */
                    java.sql.Date resultDate2 = Util.timeConvert(resume.getResume_date());
                    java.sql.Date resultDate3 = Util.timeConvert(resume.getResume_datetime());

                    Dept dept = deptClient.getDeptOne(resume.getResume_dept());
                    Position position = positionClient.getPosition(resume.getResume_position());

                    rd.setRecord_date(resultDate);
                    resume.setResume_date(resultDate2);
                    resume.setResume_datetime(resultDate3);


                    recordVo.setRecord(rd);
                    recordVo.setResume(resume);
                    recordVo.setDept(dept);
                    recordVo.setPosition(position);
                    recordVos.add(recordVo);
                }
            }

            /* redis 赋值 */
            setRedis("recordListPage",recordVos);
        }

        recordVos.forEach(System.out::println);
        return recordVos;
    }

//    @RequestMapping(value = "/getAllRecord2")
//    public HashMap<String,Object> getAllRecord2(int page, int limit) throws ParseException {
//        HashMap<String, Object> map = new HashMap<>();
//        List<RecordVo2> recordVos = new ArrayList<>();
//
////            PageHelper.startPage(page,limit);//开始分页
//            //查询获得主体档案集合【条件档案编号模糊查询，未被删除的】
//            List<Record> records = rdService.list(new QueryWrapper<Record>()
//                    .eq("record_delete", 2));
//
//            Users users=null;
//
//            for (Record rd : records) {//遍历档案集合
//                RecordVo2 recordVo2 = new RecordVo2();//创建档案界面对象
//                recordVo2.setRecord_no(rd.getRecord_no());
//                recordVo2.setRecord_date(rd.getRecord_date());
//                recordVo2.setRecord_using(rd.getRecord_using());
//                recordVo2.setRecord_id(rd.getRecord_id());
//
//                if(rd.getRecord_users()!=null){
//                    users = usersClient.getUsersById(rd.getRecord_users());
//                    if(users!=null){
//                        recordVo2.setGender(users.getGender());
//                        recordVo2.setUsername(users.getUsername());
//                        if(users.getUsers_dept()!=null){
//                            Dept dept=deptClient.getDeptOne(users.getUsers_dept());
//                            if(dept!=null){
//                                recordVo2.setDept_name(dept.getDept_name());
//                            }
//                        }
//                        if(users.getUsers_position()!=null){
//                            Position position = positionClient.getPosition(users.getUsers_position());
//                            if(position!=null){
//                                recordVo2.setPosition_name(position.getPosition_name());
//                            }
//                        }
//
//                    }
//                }
//
//
//                recordVos.add(recordVo2);
//            }
//
//            /* redis 赋值 */
////            setRedis("recordListPage",recordVos);
////        }
//
////        recordVos.forEach(System.out::println);
//        map.put("code",0);
//        map.put("data",recordVos.stream().skip((page-1)*limit).limit(limit).collect(Collectors.toList()));
//        map.put("count", recordVos.size());
//        return map;
//    }


    @RequestMapping(value = "/getOneRecord")
    public RecordVo getOneRecord(int record_Id) throws ParseException {
        System.out.println("getOneRecord()");

        RecordVo recordVo = new RecordVo();

        Record record = rdService.getOne(new QueryWrapper<Record>().eq("record_id",record_Id));
        java.sql.Date resultDate1 = Util.timeConvert(record.getRecord_date());
        record.setRecord_date(resultDate1);

        Resume resume = rmService.getOne(new QueryWrapper<Resume>().eq("resume_id",record.getRecord_resume()));

        Dept dept = deptClient.getDeptOne(resume.getResume_dept());
        Position position = positionClient.getPosition(resume.getResume_position());

        recordVo.setRecord(record);
        recordVo.setResume(resume);
        recordVo.setDept(dept);
        recordVo.setPosition(position);
        return recordVo;
    }



    /*
    * 完成一个回滚的操作
    * */

    @RequestMapping(value = "/addRecord")
    public boolean addRecord(Record record){
        System.out.println(record);
        //1、第一步，查询最新添加的简历表编号ID 2、第二部，添加档案信息

        boolean res =  rdService.addRecord(record);
        if (res) {
            this.iMessageService.send("recordListPage");
        }
        return res;
    }

    @RequestMapping(value = "/updRecord")
    public boolean updRecord(int record_id,int record_using){
//        System.out.println("updRecord()");

        Record record = new Record();
        record.setRecord_id(record_id);

        if (record_using==1)
            record.setRecord_using(2);
        else
            record.setRecord_using(1);

        boolean res = rdService.updateById(record);

        /*
        * 修改后 通过消息队列发送消息-监听方法-对redis进行重新操作
        * */
        iMessageService.send("recordListPage");
        return res;
    }


    @RequestMapping(value = "/delByRecord")
    public boolean delByRecord(int record_id){

        Record record = new Record();
        record.setRecord_delete(1);
        record.setRecord_id(record_id);

        boolean res =  rdService.updateById(record);
        iMessageService.send("recordListPage");

        return res;
    }

    @RequestMapping(value = "/send")
    public void ffFirst(){
        this.iMessageService.send("ace");
    }

    @RabbitListener(queues = "recordQueue")
    public void recordQueue(String msg){
        List<RecordVo> recordVos = null;
        System.out.println("接收到消息msg:"+msg);
        removeRedis(msg);

        try {
            recordVos = getAllRecord(0, 3, "1");
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        setRedis("recordListPage",recordVos);
    }

    /*
     * RabbitMq 实现Redis 重铸
     * */
    /*
     * 2、Redis-增删查方法
     * */

    public void removeRedis(String name){
        System.out.println("removeRedis()");
        redisUtil1.remove(name);
    }

    public void setRedis(String name,List<RecordVo> recordVos){
        System.out.println("setRedis()");
        redisUtil1.lPushAll(name,recordVos,60L*24);
    }

    public List<RecordVo> getRedis(String name,int indexPage,int pageSize){
        System.out.println("getRedis()");
        List<RecordVo> recordVos = null;
        List<Object> objects=redisUtil1.lRange(name, indexPage, pageSize);
        if(objects!=null&&objects.size()>0){
            recordVos = objects.stream().map(j->(RecordVo)j).collect(Collectors.toList());

            /*
             * 每次执行getRedis 重新为Redis赋值，进行时间的刷新，保证时间上和用户访问一致
             * */
            removeRedis(name);
            setRedis(name,recordVos);
            return recordVos;
        }

        return null;
    }

}
